# coding: utf-8
from flask import Blueprint
from flask import g, request
from xml.etree import ElementTree as etree

from leancloud import Object, Query

from tools import logging
from tools.wechatpayAPI import sign as wepaysign, createOrder, payreturn, SUCCESSXML
from agmbeta import ISLOCAL
from dbModels import Cache_dict

app = Blueprint('wechatpay', __name__)
WEPAYORDERID = '56f7a88ed342d30055aeec8f'


@app.route('/', methods=['POST', 'GET'])
@logging.log
def index():
    if request.method == 'POST' and request.data:
        xml = etree.XML(request.data)
        if not ISLOCAL:
            savelog(xml)
            if not checksign(xml):
                return 'SignFaild'
        data = xmltojson(xml)
        product_id = data.get('product_id')
        openid = data.get('openid')
        is_subscribe = data.get('is_subscribe')
        if product_id and openid:
            orderdict = Query(Cache_dict).get(WEPAYORDERID).get('content')
            d = orderdict.get(product_id)
            if d:
                # if d.get('is_subscribe'):
                    # if is_subscribe == 'N':
                        # return payreturn(None, True, u'请先关注音速风暴路轨赛车公众号，再进行扫码支付，谢谢！')
                if is_subscribe == 'N':
                    if d['no_subscribe_fee'] <= 0:
                        return payreturn(None, True, u'请先关注音速风暴路轨赛车公众号，再进行扫码支付，谢谢！')
                    total_fee = d['no_subscribe_fee']
                else:
                    if d['total_fee'] <= 0:
                        return payreturn(None, True, u'此二维码当前失效，请联系音速风暴官方人员确认!')
                    total_fee = d['total_fee']
                attach = d.get('attach')
                ret = createOrder(product_id, openid, total_fee=total_fee, body=d['body'], attach=attach)
            else:
                return payreturn(None, True, u'此二维码当前失效，请联系音速风暴官方人员确认!')
                ret = createOrder(product_id, openid)
            prepay_id = etree.XML(ret).find('prepay_id').text
            return payreturn(prepay_id)
               
    print 'WechatPay-URL:', request.url, request.method, request.data
    return 'WechatPay!'
    
@app.route('/success', methods=['POST', 'GET'])
@logging.log
def sucess():
    if request.method == 'POST' and request.data:
        xml = etree.XML(request.data)
        savelog(xml, 'WepaySuccess')
        if not checksign(xml):
            return 'SignFaild'
        data = xmltojson(xml)
        if data.get('return_code') == 'SUCCESS':
            return SUCCESSXML        
        
    print 'WechatPaySucess-URL:', request.url, request.method, request.data
    return 'WechatPaySuccess!'
    
@app.route('/test', methods=['POST', 'GET'])
def test():
    print 'WechatPayTest-URL:', request.url, request.method, request.data
    return 'WechatPayTest!'    
    
def savelog(xml, logname='WepayLog'):
    WepayLog = Object.extend(logname)
    log = WepayLog()
    for t in xml:
        log.set(t.tag, t.text or "")
    if logname == 'WepaySuccess':
        saveProductId(log, xml)
    log.save()
    
def saveProductId(log, xml):
    out_trade_no = xml.find('out_trade_no').text
    orders = Query(Object.extend('WepayCreateorder')).equal_to('out_trade_no', out_trade_no).find()
    if orders:
        product_id = orders[0].get('product_id')
        log.set('product_id', product_id)

def checksign(xml):
    data = {}
    sign = ''
    for t in xml:
        if t.tag != 'sign':
            data[t.tag] = t.text
        else:
            sign = t.text
            
    return sign == wepaysign(data)
    
def xmltojson(xml):
    data = {}
    for t in xml:
        data[t.tag] = t.text
    return data